//
//  LXNet+RxSwift.swift
//  LXMoyaHelper
//
//  Created by yoctech on 2021/8/6.
//

import Foundation
import Moya
import RxSwift

extension LXNet: ReactiveCompatible {}

public extension Reactive where Base: TargetType {
    /// TargetType使用RxSwift快速发起请求,使用LXNetManager里配置的provider
    func startRequest() -> Single<Response> {
        return LXNetManager.config.provider.rx.request(.target(base), callbackQueue: LXNetManager.config.callbackQueue)
    }
    /// TargetType使用RxSwift快速发起带进度的请求,使用LXNetManager里配置的provider
    func startRequestWithProgress() -> Observable<ProgressResponse> {
        return LXNetManager.config.provider.rx.requestWithProgress(.target(base), callbackQueue: LXNetManager.config.callbackQueue)
    }
    
}


public extension ObservableType where Element == Response {
    
    /// 将Response使用转换器转换成指定的模型T
    /// - Parameters:
    ///   - type: 模型T的Class
    ///   - serializer: 转换器,默认使用LXNetManager配置的转换器
    /// - Returns: Observable`<T>`
    func serializeObject<T:LXJsonMapper>(_ type: T.Type, serializer: LXMoyaResultSerializer = LXNetManager.config.serializeHandle) -> Observable<T> {
        return flatMap { Observable.just(try serializer.serialize(response: $0)) }
    }
    /// 将Response使用转换器转换成指定的模型T数组`[T]`
    /// - Parameters:
    ///   - type: 模型T的Class
    ///   - serializer: 转换器,默认使用LXNetManager配置的转换器
    /// - Returns: Observable`<[T]>`
    func serializeArray<T:LXJsonMapper>(_ type: T.Type, serializer: LXMoyaResultSerializer = LXNetManager.config.serializeHandle) -> Observable<[T]> {
        return flatMap { Observable.just(try serializer.serializeArray(response: $0)) }
    }

}

public extension PrimitiveSequence where Trait == SingleTrait, Element == Response {
    /// 将Response使用转换器转换成指定的模型T
    /// - Parameters:
    ///   - type: 模型T的Class
    ///   - serializer: 转换器,默认使用LXNetManager配置的转换器
    /// - Returns: Single`<T>`
    func serializeObject<T:LXJsonMapper>(_ type: T.Type, serializer: LXMoyaResultSerializer = LXNetManager.config.serializeHandle) -> Single<T> {
        return flatMap { Single.just(try serializer.serialize(response: $0)) }
    }

    /// 将Response使用转换器转换成指定的模型T数组`[T]`
    /// - Parameters:
    ///   - type: 模型T的Class
    ///   - serializer: 转换器,默认使用LXNetManager配置的转换器
    /// - Returns: Single`<[T]>`
    func serializeArray<T:LXJsonMapper>(_ type: T.Type, serializer: LXMoyaResultSerializer = LXNetManager.config.serializeHandle) -> Single<[T]> {
        return flatMap { Single.just(try serializer.serializeArray(response: $0)) }
    }

}
